#! /usr/bin/python3

import youdao
import sendtext
import json
import os
import sys
import sounddevice as sd


class App():
    def __init__(self):
        self.freq = 16000
        self.duration = 0.4
        sd.default.channels = 1
        sd.default.dtype = 'int16'
        sd.default.samplerate = self.freq

    def init_youdao(self, cfg):
        self.youdao = youdao.YouDaoClient(cfg)
        pass

    def init_sendtext(self, show_origin, show_trans):
        self.youdao.send_text = sendtext.SendText(show_origin, show_trans)

    def run(self):
        print("start record...")

        def on_record(indata, frames, time, status):
            if any(indata):
                self.youdao.push(indata)
            else:
                print('no input')

        with sd.InputStream(dtype='int16', samplerate=self.freq, blocksize=int(self.freq*self.duration*2), callback=on_record, ):
            while True:
                res = input()
                if res in ('q', 'Q'):
                    break

if __name__ == '__main__':
    app_path = os.path.abspath(sys.argv[0]+'/..')
    cfg_path = app_path+'/config.json'
    cfg = json.load(open(cfg_path, 'r'))
    print(cfg)    

    app = App()

    youdao_cfg = cfg['youdao']
    app.init_youdao(youdao_cfg)

    send_cfg = cfg['send']
    app.init_sendtext(send_cfg['origin'], send_cfg['trans'])

    while True:
        app.run()
